package com.wntime.simulator.device.register;

import com.ghgande.j2mod.modbus.procimg.SimpleRegister;
import com.wntime.simulator.device.SimulationField;
import com.wntime.simulator.utils.JacksonUtils;
import com.wntime.simulator.utils.NumberUtils;
import com.wntime.simulator.utils.TimeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.ThreadUtils;

import java.time.Duration;
import java.util.List;
import java.util.Map;

public class RangeSimpleRegister extends SimpleRegister {
//    public RangeSimpleRegister(Number min, Number max) {
//        super(NumberUtils.randomNumber(min.intValue(),max.intValue()).intValue());
//        Runnable runnable = () -> {
//            while (true) {
//                this.setValue(NumberUtils.randomNumber(min.intValue(), max.intValue()).intValue());
//                try {
//                    Thread.sleep(1000);
//                } catch (InterruptedException e) {
//                    throw new RuntimeException(e);
//                }
//            }
//
//        };
//        new Thread(runnable).start();
//    }

    public RangeSimpleRegister(SimulationField field) {
        super(field.getBefore());
        Runnable runnable = () -> {
            while (true) {
                String extendInfo = field.getExtendInfo();
                if (StringUtils.isNotBlank(extendInfo)) {
                    try {
                        List<Map<String, Object>> maps = JacksonUtils.json2list(extendInfo);
                        for (Map<String, Object> map : maps) {
                            String start = (String) map.get("start");
                            String end = (String) map.get("end");
                            Object min = map.get("min");
                            Object max = map.get("max");
                            if (TimeUtils.compareTime(start, end)) {
                                Number number = NumberUtils.randomNumber(Integer.parseInt(min.toString()), Integer.parseInt(max.toString()));
                                this.setValue(number.intValue());
                            }
                        }
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    int before = field.getBefore();
                    int after = field.getAfter();
                    this.setValue(NumberUtils.randomNumber(before, after).intValue());
                }
                ThreadUtils.sleepQuietly(Duration.ofSeconds(1));
            }
        };
        new Thread(runnable).start();
    }
}
